
// //请求截图
// if(!requestScreenCapture(true)){
//     toast("请求截图失败");
//     exit();
// }else{
//     log('截图权限')
// }
$images.requestScreenCapture();

var imgs = {}
imgs.find = function(name){

    try {
        //截图
        // 初始化ColorMapping
        let ColorMapping = $colors.mapping;
        // 创建ColorMapping实例
        let cm = new ColorMapping();
        // 截屏
        let img = $images.captureScreen();
        // 初始化颜色映射
        cm.reset(img);
        let cd = d[name]

        let newoption = cd[2]



        width = newoption["region"][2] - newoption["region"][0]
        height = newoption["region"][3] - newoption["region"][1]

        log(cd[2], newoption, width, height)

        var p = cm.findMultiColors(cd[0],cd[1], { region:[newoption["region"][0],newoption["region"][1],width,height],threshold: 20 } )
        cm.recycle();

        if ( p ){///////////////
            log('找到=> '+ name)
            if ( cd[3] ){
                if (!cd[4]) { cd[4] = 1 }
                f.click(p.x,p.y,cd[4],name )
            }
            return p
        }
    } catch (error) {
        console.log(error)
    }

}


//新版基础函数
var f = {
    init:function() {
        log("程序初始化")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (x,y,x1,y1,times){
        swipe(x,y,x1,y1,times);
        sleep(1000);
    }
}
f.init()


//批查打印app参数
function printAll( ways ) {
    if (!ways){
        ways = 'className'
    }
    if (ways = 'className'){
        var all_Info = classNameMatches(/.*/).find();
    }else
    if (ways == 'text'){
        var all_Info = textMatches(/.*/).find();
    }else
    if (ways == 'id'){
        var all_Info = idMatches(/.*/).find();
    }else{
        eval( 'var all_Info = ' + ways + '.find();'  )
    }
    
    if ( all_Info ){
        for (var i = 0;i<all_Info.length;i++){
            var d = all_Info[i];
            log(i,d.id(),d.text(),"desc:"+d.desc(),'"className":"'+d.className()+'"',
            "clickable->"+d.clickable(),'selected->'+selected(),"depth->"+d.depth(),
            d.bounds().centerX(),d.bounds().centerY())
        }
    }else{
        log('没有找到任何相关的节点')
    }
}


// printAll()



//河马ip
function hmip(){
    var result = shell("ipclient faa31f81bfea4124995972d5dc016b57 1", true);
    // console.show();
    // log(result);
    if(result.code == 0){
        toastLog("vpn 执行成功");
      return true
    }else{
        toastLog(result)
        toastLog("vpn 执行失败！请到控制台查看错误信息");
    }
}


//设备大师
function sbds(){
    let fix = false
    var start = false
    var timeLine = new Date().getTime()
    while ( new Date().getTime() - timeLine < 5 * 60 * 1000 ) {

        if ( f.active( appinfo.sbdsbid , 5)  ){

            if (fix && f.ms({"text":"修改设备"},false,rd(2,3) )){
                return true
            }else
            if ( f.ms({"text":"修改设备"},true,rd(2,3) )   ){
                start = true;
            }else if ( start && f.ms("id","brand",true,rd(2,3) ) ){

                var phonelist = [ "XIAOMI","HUAWEI","SAMSUNG","HONOR","vivo"]
                if ( f.ms({"text":phonelist[rd(0,4)],"depth":4},true,rd(1,2)) ) {
                    f.ms("text","下一步",true,rd(2,3))
                }else{
                    f.ms("id","back",true,rd(2,3))
                }
                
            }else if( start && f.ms("text","立即清理",false,rd(2,3)) ){
                f.ms("text","以吾之力",true,1)
                f.ms("text","QQ浏览器",true,1)

                if ( f.ms("text","立即清理",true,rd(10,15)) ){
                    fix = true
                }
            }else{
                f.ms("id","back",true,rd(2,3))
            }
        }
        sleep(1000);
    }
}


//设备大师
function sbdsJk(){

    f.active(appinfo.sbdsbid, 8)
    var result = shell("setphone" ,true);

    // console.show();
    log(result);


    if(result.code == 0){
        toastLog("一键新机 执行成功")
    }else{
        toastLog("一键新机 执行失败！请到控制台查看错误信息")
    }

    eval( 'var result = shell("pm clear '+ appinfo.bid +'",true)'  )
    eval( 'var result = shell("pm clear '+ appinfo.llq +'",true)'  )
    // var result = shell("pm clear com.youxiang.soyoungapp",true)
    log(result);
    if(result.code == 0){
        toastLog("一键清理 执行成功");
        home()
        return true
    }else{
        toastLog("一键清理 执行失败！请到控制台查看错误信息");
    }


}

//设备大师参数信息
function getsbds() {
    let fix = false;
    var start = false;
    var timeLine = new Date().getTime();
    while (new Date().getTime() - timeLine < 3 * 60 * 1000) {
        if (  f.active(appinfo.sbdsbid, 5)  ) {
            
            if ( f.ms({"text":"当前设备"} ) ){
                log("设备信息界面");
                appinfo.imei = id("imei").findOne(100).text();
                appinfo.oaid = id("android_id").findOne(100).text();
                // appinfo.device = id("phone_model").findOne(100).text();
                // appinfo.brand = id("phone_brand").findOne(100).text();

                // console.show()
                log( appinfo );
                home()
                sleep(1000)
                return true;
            }

        }
    }
}

//上传idfa
function Idfa(other){
    let postArr = {};
    postArr['service'] = 'Idfa.idfa';
    postArr['name'] = appinfo.name;
    postArr['idfa'] = appinfo.imei || new Date();
    postArr['password'] = device.getIMEI();
    postArr['other'] = other ? other : "成功";
    let data = f.post("http://wenfree.cn/api/Public/idfa/",postArr);
    toastLog("上传成功")
}


//主程序
function main(){

    f.active(appinfo.bid, 5)
    var timeLine = new Date().getTime();
    while (new Date().getTime() - timeLine < (20+f.rd(1,3)) * 1000) {
        
        f.ms({"text":"同意"},true,3)
        f.ms({"textMatches":"开启.*"},true,3)


        f.ms({"textMatches":"允许.*"},true,2)
        f.ms({"textMatches":"允许.*"},true,2)

        f.ms({"textMatches":".*UC浏览器.*"},true,2)
        f.ms({"textMatches":"始终"},true,2)
        f.ms({"textMatches":"同意.*"},true,2)


        if (f.ms({"textMatches":".*为空.*"},true,2)){
            // Idfa("为空")
            // sleep(20*1000)
            return
        }

        if (f.ms({"textMatches":".*失败.*|.*错误.*|.*黑.*"},true,2)){
            Idfa("ip拉黑")
            return
        }


        sleep(2000)
        f.click(width/2,height*0.85,2,"下载")
    }

    f.active(appinfo.bid, 5)
    if ( f.ms({"textMatches":"下载工作完成"},true,2) ){
        return true
    }

}

function checkIp(){
    url = "http://wenfree.cn/api/Public/idfa/?service=Ip.Checkip&ip="
    r = f.post(url,{})
    log(r)
    if (r){
        r = JSON.parse(r)
        if ( r.data.state == "ok"){
            toastLog(r.data.ip + "可以使用")
            return true
        }
    }
}


// 正式开始编代码
var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);
var appinfo = {}
appinfo.name = "DK-game";
appinfo.bid = "com.ntrance.dkorigincoinglobal";
appinfo.link = "https://app.dkmobile-genesis.one/";
appinfo.llq = "com.android.chrome";
appinfo.gzbid = "com.deruhai.guangzi";
appinfo.sbdsbid = "com.longene.setcardproperty";
info ={};



function urlopen(){
    for ( var j=0;j<3;j++){
        sleep(2000)
        app.openUrl(appinfo.link)
        let i = 20
        while ( i > 0){
            f.ms({"text":"接受并继续"}, true)
            f.ms({"text":"继续使用 Google"}, true)
            if ( f.ms({"text":"取消"}, true, 2) ){
                home()
                return true
            }
            i--
            sleep(1000)
        }
    }
}



// sbdsJk()

// checkIp()
var d ={}
// d['DK']=["#3c342f",[[-11,-17,"#531248"],[-10,-30,"#ffffff"],[-5,27,"#dfcfb1"],[-26,24,"#2a0a1c"]], {region:[ 10,311,695,1220],threshold:20 },true,2 ]
d['DK']=["#fffbf6",[[-9,-4,"#54124b"],[-4,-28,"#2c0a22"],[-20,42,"#210a1b"],[-9,34,"#f3e6c9"]], {region:[ 49,341,621,1186],threshold:20 },true,2 ]
d['DK-OK']=["#394459",[[11,1,"#d5d6d8"],[-70,-19,"#455b7a"],[-207,-240,"#cfa102"]], {region:[ 398,223,863,553],threshold:20 },true,2 ]
d['DK-download']=["#394459",[[11,1,"#ffffff"],[2,-115,"#ebad1f"],[-287,-20,"#353535"],[-96,-128,"#0d1317"]], {region:[ 429,310,861,506],threshold:20 },true,2 ]
d['DK-isOK']=["#a95819",[[104,6,"#fbf9f8"],[144,-7,"#b36018"],[84,-267,"#fce08b"],[76,-254,"#cda15b"]], {region:[ 468,280,810,618],threshold:20 },false,2 ]

sleep(1000)
// imgs.find("DK")

f.ms({"text":"允许"},true,2)



function all(){
    hmip()

    if ( sbdsJk() ){
        if ( true || getsbds() ){
    
            if ( urlopen() ){
                
                home()
                let i = 600
                while ( i > 0 ){
                
                    f.ms({"text":"允许"},true,1)
                    imgs.find("DK")
                    imgs.find("DK-OK")
                    imgs.find("DK-download")
                    if ( imgs.find("DK-isOK") ) {
                        Idfa('ok')
                        break
                    }
                
                    sleep(500)
                    i = i - 1
                    f.ms({"textMatches":".*关闭.*"},true,2)
                }
                
                f.ms({"textMatches":".*关闭.*"},true,2)
    
            }
        }
    }
    

}


while ( true ){
    try {
        all()
    } catch (error) {
        
    }

}



